﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Threading;
using System.Reflection; // 引用这个才能使用Missing字段
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.Web;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.IO;
using CCWin;
using Newtonsoft.Json;
using LitJson;
using Newtonsoft.Json.Linq;

namespace weiqijiance.灯光仪
{
    public  class libass
    {

        public int iLIGQ;//光强
        public float fLIZYPY;//远光左右偏移
        public float fLISXPY;//远光上下偏移
        public int iLIDG;//灯高
        public int iLIGQ2;//近光光强
        public float fLIZYPY2;//近光左右偏移
        public float fLISXPY2;//近光上下偏移
        public int iLIDG2;//灯高

        public SerialPort comLI = new SerialPort();//灯光仪串口
        private SerialPort comNO = new SerialPort();//声级串口



        public bool bguiwei=false;//灯光仪归位是否成功
        public bool byuanguang;//主灯远光是否检测完成
        public bool byuanguangfudeng;//副灯远光是否检测完成
        public bool bjingguang;//主灯近光是否检测完成
        public bool b进入近光连续测量;//进入近光连续测量
        public bool b进入远光连续测量;//进入远光连续测量
        public bool btuichu;
        public string sjcdg;//当前检测的灯光
        public bool bjcshibai;//检测失败：寻不到光
        public bool bqushu = false;

        public float fshengji;//串口声级数据

        // /声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        //声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public string sPath = "";
        //ini文件
        public void Ini(string path)
        {
            this.sPath = path;
        }
        public void Writue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
        public void init()
        {

            iniclass objini = new iniclass();
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\安综检仪表配置.ini";
            string path1 = string.Format(@"{0}", path);
            objini.Ini(path1);
            string sSetCom = objini.ReadValue("灯光", "灯光仪串口设置").Trim();
            if (sSetCom != "")
            {
                //bgas = true;
                openCOM(sSetCom);
                comLI.ReadTimeout = 500;
                
                //comLI.DataReceived += comLI_DataReceived;
            }

          
        }

        public virtual bool sendLIcom(int cmd)//发送指令给灯光仪串口
        {
            return true;
           
        }

     
        //  声级
        void comNO_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (comNO.IsOpen)
            {
                int n = comNO.BytesToRead;//
                byte[] buf1 = new byte[n];//声明一个临时数组存储当前来的串口数据  
                byte[] buf = new byte[n];
                comNO.Read(buf1, 0, n);
                if (n > 2)
                {
                    buf = null;
                    buf = new byte[n];
                    buf1.CopyTo(buf, 0);
                    float.TryParse(string.Format("{0}", (buf[2] + buf[3] * 0.1)), out fshengji);
                }
            }

        }

        public virtual bool openCOM(string sSet1)//打开串口
        {

            string[] szbzlCOM = new string[5];
            if (sSet1.Length > 0)
                szbzlCOM = sSet1.Split(':');
            //打开串口
            comLI.PortName = szbzlCOM[0];
            comLI.BaudRate = Convert.ToInt32(szbzlCOM[1]);

            comLI.NewLine = "/r/n";
            comLI.RtsEnable = true;//根据实际情况吧。 
            comLI.ReadTimeout = 300;//读取数据延时，避免读取不全数据

            if (szbzlCOM[3] == "0")
                comLI.Parity = Parity.None;
            else
                comLI.Parity = Parity.Even;
            // ////添加事件注册  
            //  comm.DataReceived += comm_Data;

           

            try
            {
                comLI.Open();
            }
            catch (Exception )
            {
                //lzj20200706   MessageBox.Show(string.Format("{0}\n请检查电脑的串口故障", ex.Message));
                return false;
            }
            return true;
        }

        public void Write(string path, string str)
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write((str).ToString());
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
    }
}
